package com.ferdict;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sourceforge.stripes.ajax.JavaScriptBuilder;

public class JsonResolution {
    private JsonBuilder builder;

    /**
     * Constructs a new JavaScriptResolution that will convert the supplied object to JavaScript.
     *
     * @param rootObject an Object of any type supported by {@link JavaScriptBuilder}. In most cases
     *        this will either be a JavaBean, Map, Collection or Array, but may also be any one of
     *        the basic Java types including String, Date, Number etc.
     * @param objectsToExclude Classes and/or property names to exclude from the output.
     */
    public JsonResolution(Object rootObject, Object... objectsToExclude) {
        this.builder = new JsonBuilder(rootObject, objectsToExclude);
    }

    /**
     * Adds one or more properties to the list of types to exclude when translating
     * to JavaScript.
     *
     * @param property one or more property names to exclude
     * @return the JavaScripResolution instance to simplify method chaining
     */
    public JsonResolution addPropertyExclusion(final String... property) {
        this.builder.addPropertyExclusion(property);
        return this;
    }

    /**
     * Adds one or more classes to the list of types to exclude when translating
     * to JavaScript.
     *
     * @param clazz one or more classes to exclude
     * @return the JavaScripResolution instance to simplify method chaining
     */
    public JsonResolution addClassExclusion(final Class<?>... clazz) {
        this.builder.addClassExclusion(clazz);
        return this;
    }

    /**
     * Converts the object passed in to JavaScript and streams it back to the client.
     */
    public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/javascript");
        this.builder.build(response.getWriter());
        response.flushBuffer();
    }

}
